package com.springboot.cloud.demos.producer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.cloud.demos.producer.dao.FollowMapper;
import com.springboot.cloud.demos.entity.param.FollowQueryParam;
import com.springboot.cloud.demos.entity.po.Follow;
import com.springboot.cloud.demos.producer.service.IFollowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
@RefreshScope
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Value("${producer.follow:123}")
    private String value;

    @Override
    @Caching(evict = {
            @CacheEvict(value = "follow",allEntries = true),
            @CacheEvict(value = "user" , allEntries = true)
    })
    public boolean add(Follow follow) {
        return this.save(follow);
    }


    @Override
    public boolean delete(String id) {
        return this.removeById(id);
    }

    @Override
    @Caching(evict = {
    @CacheEvict(value = "follow",allEntries = true),
    @CacheEvict(value = "user" , allEntries = true)
    })
    public Integer deleteByMap(String userId ,String followUserId) {
        QueryWrapper<Follow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("follow_user_id", followUserId);
        return this.getBaseMapper().delete(queryWrapper);
    }

    @Override
    public boolean update(Follow follow) {
        return this.updateById(follow);
    }

    @Override
    public Follow get(String id) {
        log.info("value:{}", value);
        return this.getById(id);
    }

    @Override
    public List<Follow> query(FollowQueryParam param) {
        QueryWrapper<Follow> queryWrapper = param.build();
        queryWrapper.eq("user_id", param.getUserId());
        queryWrapper.eq("follow_user_id", param.getFollowUserId());
        return this.list(queryWrapper);
    }

    @Override
    @Cacheable(value = "follow", key = "#root.targetClass+'-'+#userId+#followUserId")
    public Follow query(String userId, String followUserId) {
        QueryWrapper<Follow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("follow_user_id", followUserId);
        List<Follow> list = this.list(queryWrapper);
        return list.isEmpty() ? null : list.get(0);
    }

}
